/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.product.web.AddOnProductAction
   Module Description   :

   Date Created      : 2009/12/15
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.product.web;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.product.entity.AddOnProduct;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;

/**
 * @author ellen.li
 * 
 */
public class AddOnProductAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = -6014622757960381106L;
	private final Logger logger = LoggerFactory.getLogger(AddOnProductAction.class);
	private ProductService productService;
	@Autowired
	private BaseManager baseMgr;
	private SimplePager pager;
	CommonCriteria crit;
	private List<String> addonproducts;
	private List<String> addOnProductsByMainId;// 未開始:1
	private List<String> addOnProductsByMainId2;// 進行中:2
	private List<String> addOnProductsByMainId3;// 已結束:3
	private String addonId;
	private AddOnProduct addOnProduct;
	private String productNameDataExist;
	private String mainProductId;
	private String mainSubFlag;
	private Product product;
	private Shelf shelfMain;
	private Shelf shelfSub;
	private String today;
	private Product mainProduct;
	private Product subProduct;
	private String markMainProductId;

	@Resource
	private LogService logService;

	@Resource
	private ShelfService shelfService;

	/* 頁面參數 */
	private String mainProductIdParam;
	private String addonProductIdParam;
	private String addonstatus;
	private String finalAddOnData;

	private CommonCriteria criteria;
	private List<AddOnProduct> addOnProductList;
	private String editAddOnPrice;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	/* 新增:搭售 / 加價購 / 贈品 / 加一元多一件 */
	public String add() {
		addOnProduct = new AddOnProduct();
		addonId = null;
		return "edit";
	}

	public String del() throws Exception {
		if (StringUtils.isNotBlank(addonId)) {
			addOnProduct = productService.getAddOnProductById(Long.valueOf(addonId));
			addOnProduct.setIsDelete("Y");
			productService.saveAddOnProduct(addOnProduct);
		}
		return "jsonFindProductName";
	}

	/* 編輯:搭售 / 加價購 / 贈品 / 加一元多一件 */
	public String edit() throws Exception {
		if (addonId != null || addOnProduct.getAddonId() != null) {
			try {
				if (StringUtils.isNotBlank(String.valueOf(addonId))) {
					addOnProduct = productService.getAddOnProductById(Long.valueOf(addonId));
				} else {
					addOnProduct = productService.getAddOnProductById(addOnProduct.getAddonId());
				}
				// 找出主商品的次商品
				addOnProductsByMainId = productService.getAddOnProductList(addOnProduct.getMainProductId(), "", "1", 0, -1);// 1:未開始
				addOnProductsByMainId2 = productService.getAddOnProductList(addOnProduct.getMainProductId(), "", "2", 0, -1);// 2:進行中
				addOnProductsByMainId3 = productService.getAddOnProductList(addOnProduct.getMainProductId(), "", "3", 0, -1);// 3:已結束

				shelfMain = shelfService.getActiveShelfByProductId(addOnProduct.getMainProductId());
				shelfSub = shelfService.getActiveShelfByProductId(addOnProduct.getAddOnProductId());

				mainProduct = productService.get(addOnProduct.getMainProductId());
				subProduct = productService.get(addOnProduct.getAddOnProductId());
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		return "edit";
	}

	/**
	 * 查询商品名称
	 * 
	 * @return
	 * @throws Exception
	 */
	public String findProductName() throws Exception {
		if (StringUtils.isNotBlank(mainProductId)) {
			Product mainProd = productService.get(mainProductId);
			if (null == mainProd) {
				productNameDataExist = "查无商品资料(或无该权限查看)";
			} else {
				if (mainProd.getProductType() == 7) {
					productNameDataExist = "此商品为限定立即购买商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
							+ ServerValue.getMidContextPath() + "/product/edit.do?productId=" + mainProductId + ">「查询此商品」</a> ";
				} else if (StringUtils.equalsIgnoreCase("Y", mainProd.getIsScm())) {
					productNameDataExist = "请查看商品SCM状态，SCM转单商品不能搭售";
				} else {
					CommonCriteria crit = new CommonCriteria();
					crit.addEq("productId", mainProductId);
					if (mainSubFlag.equals("main")) {
						crit.addEq("productType", Integer.parseInt("0"));
					}
					if (productService.getList(0, -1, crit, null).size() > 0) {
						product = productService.get(mainProductId);
						if (null == product) {
							productNameDataExist = "查无商品资料(或无该权限查看)";
						} else {
							if (mainSubFlag.equals("sub")) {
								// 次商品可为：一般、加购、配件
								if (product.getProductType() == 0 || product.getProductType() == 2 || product.getProductType() == 3) {
									crit = new CommonCriteria();
									crit.addEq("productId", mainProductId);
									crit.addEq("isDelete", "N");
									int prodSpecSize = productService.getSpecificationList(0, -1, crit, null).size();
									if (prodSpecSize > 1) {
										if ("N".equals(ServerValue.getUseDoubleSpec())) {
											productNameDataExist = "搭售商品只能有一個規格";
										} else {
											if (StringUtils.isNotBlank(editAddOnPrice)) {
												if ("0".equals(editAddOnPrice)) {
													productNameDataExist = "搭售商品只能有一個規格";
												} else {
													productNameDataExist = product.getProductName();
												}
											}
										}
									} else if (StringUtils.equalsIgnoreCase("Y", product.getIsDelete())) {
										productNameDataExist = "搭售商品已被删除";
									} else if (StringUtils.equalsIgnoreCase("Q", product.getIsDelete())) {
										productNameDataExist = "搭售商品的销售状态为可查询不可销售";
									} else {
										productNameDataExist = product.getProductName();
									}
								} else {
									if (product.getProductType() == 6) {
										Shelf shelf = shelfService.getActiveShelfByProductId(mainProductId);
										if (null == shelf) {
											productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
													+ ServerValue.getMidContextPath() + "/pickProduct/editProduct.do?productIdParam="
													+ mainProductId + ">「查询此商品」</a> ";
										} else {
											productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
													+ ServerValue.getMidContextPath() + "/pickProduct/editProduct.do?shelfIdParam="
													+ shelf.getShelfId() + "&productIdParam=" + mainProductId + ">「查询此商品」</a> ";
										}
									} else {
										productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
												+ ServerValue.getMidContextPath() + "/product/edit.do?productId=" + mainProductId
												+ ">「查询此商品」</a> ";
									}
								}
							} else {
								productNameDataExist = product.getProductName();
							}
						}
					} else {
						if (product.getProductType() == 6) {
							Shelf shelf = shelfService.getActiveShelfByProductId(mainProductId);
							if (null == shelf) {
								productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
										+ ServerValue.getMidContextPath() + "/pickProduct/editProduct.do?productIdParam=" + mainProductId
										+ ">「查询此商品」</a> ";
							} else {
								productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
										+ ServerValue.getMidContextPath() + "/pickProduct/editProduct.do?shelfIdParam="
										+ shelf.getShelfId() + "&productIdParam=" + mainProductId + ">「查询此商品」</a> ";
							}
						} else {
							productNameDataExist = "此商品非一般商品，无法提供搭售设定;<a href=" + ServerValue.getMidHostname()
									+ ServerValue.getMidContextPath() + "/product/edit.do?productId=" + mainProductId + ">「查询此商品」</a> ";
						}
					}
				}
			}
		}
		return "jsonFindProductName";
	}

	/**
	 * @return the addonId
	 */
	public String getAddonId() {
		return addonId;
	}

	/**
	 * @return the addOnProduct
	 */
	public AddOnProduct getAddOnProduct() {
		return addOnProduct;
	}

	/**
	 * @return the addonProductIdParam
	 */
	public String getAddonProductIdParam() {
		return addonProductIdParam;
	}

	/**
	 * @return the addonproducts
	 */
	public List<String> getAddonproducts() {
		return addonproducts;
	}

	/**
	 * @return the addOnProductsByMainId
	 */
	public List<String> getAddOnProductsByMainId() {
		return addOnProductsByMainId;
	}

	/**
	 * @return the addOnProductsByMainId2
	 */
	public List<String> getAddOnProductsByMainId2() {
		return addOnProductsByMainId2;
	}

	/**
	 * @return the addOnProductsByMainId3
	 */
	public List<String> getAddOnProductsByMainId3() {
		return addOnProductsByMainId3;
	}

	/**
	 * @return the addonstatus
	 */
	public String getAddonstatus() {
		return addonstatus;
	}

	/**
	 * @return the finalAddOnData
	 */
	public String getFinalAddOnData() {
		return finalAddOnData;
	}

	public Product getMainProduct() {
		return mainProduct;
	}

	/**
	 * @return the mainProductId
	 */
	public String getMainProductId() {
		return mainProductId;
	}

	/**
	 * @return the mainProductIdParam
	 */
	public String getMainProductIdParam() {
		return mainProductIdParam;
	}

	public String getMainSubFlag() {
		return mainSubFlag;
	}

	/**
	 * @return the pager
	 */
	public SimplePager getPager() {
		return pager;
	}

	/**
	 * @return the product
	 */
	public Product getProduct() {
		return product;
	}

	/**
	 * @return the productNameDataExist
	 */
	public String getProductNameDataExist() {
		return productNameDataExist;
	}

	/**
	 * @return the productService
	 */
	public ProductService getProductService() {
		return productService;
	}

	public Shelf getShelfMain() {
		return shelfMain;
	}

	public Shelf getShelfSub() {
		return shelfSub;
	}

	public Product getSubProduct() {
		return subProduct;
	}

	public String getToday() {
		return today;
	}

	/* 列表:搭售 / 加價購 / 贈品 / 加一元多一件 */
	public String list() throws Exception {
		crit = new CommonCriteria();
		int entitySize = 0;
		entitySize = productService.getAddOnProductListSize(mainProductIdParam, addonProductIdParam, addonstatus)
				.intValue();
		pager.setTotalSize(entitySize);
		addonproducts = productService.getAddOnProductList(mainProductIdParam, addonProductIdParam, addonstatus, pager
				.getCurrentPage()
				* pager.getPageRecord(), pager.getPageRecord());
		// mainProductIdParam = "";
		// addonProductIdParam = "";
		return "list";
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (pager == null) {
			pager = new SimplePager();
		}
		pager.setPageRecord(20);// defaut 20
		if (StringUtils.isBlank(today)) {
			today = DateUtil.convertDateToString("yyyy,MM - 1,dd", DateUtil.getToday().getTime());
		}
	}

	/**
	 * 儲存:搭售 / 加價購 / 贈品 / 加一元多一件*
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		DateFormat format = new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP_HH_MM);
		String[] splitData = finalAddOnData.split(";");
		for (int i = 0; i < splitData.length; i++) {
			String[] sUpdate = splitData[i].split(",");
			if (sUpdate[0].equals("")) {// addonid為空時,表示新增
				addOnProduct = new AddOnProduct();
				// 在設定搭售時是否反向要檢查是否為N選M or 搭售
				Product mProduct = productService.get(sUpdate[1]);
				if (null == mProduct) {
					addActionError("查无商品资料(或无该权限查看)");
					return "edit";
				} else {
					if ("1".equals(String.valueOf(mProduct.getProductType()))
							|| "6".equals(String.valueOf(mProduct.getProductType()))) {
						addActionError("商品型态不可为预购或N選M");
						return "edit";
					}
					Product aProduct = productService.get(sUpdate[2]);
					if (null == aProduct) {
						addActionError("查无商品资料(或无该权限查看)");
						return "edit";
					} else {
						if ("1".equals(String.valueOf(aProduct.getProductType()))
								|| "6".equals(String.valueOf(aProduct.getProductType()))) {
							addActionError("商品型态不可为预购或N選M");
							return "edit";
						}
					}
					addOnProduct.setMainProductId(sUpdate[1]);
					addOnProduct.setAddOnProductId(sUpdate[2]);
					addOnProduct.setAddOnPrice(new BigDecimal(sUpdate[3]).setScale(1, BigDecimal.ROUND_FLOOR));
					addOnProduct.setStartDate(format.parse(sUpdate[4]));
					addOnProduct.setEndDate(format.parse(sUpdate[5]));
					addOnProduct.setIsEnable(sUpdate[6]);
					addOnProduct.setAddOnDesc(sUpdate[7]);
					addOnProduct.setApplyMemberRank(sUpdate[8]);
					addOnProduct.setIsDelete("N");
					productService.saveAddOnProduct(addOnProduct);
					logService.save(getClass().getSimpleName(), "save", addOnProduct);
				}
			} else {// addonid不為空時,表示修改
				addOnProduct = productService.getAddOnProductById(Long.valueOf(sUpdate[0]));
				// 在設定搭售時是否反向要檢查是否為N選M or 搭售
				Product mProduct = productService.get(sUpdate[1]);
				if (null == mProduct) {
					addActionError("查无商品资料(或无该权限查看)");
					return "edit";
				} else {
					if (mProduct.getProductType() == 1 || mProduct.getProductType() == 6) {
						addActionError("商品型态不可为预购或N選M");
						return "edit";
					}
					Product aProduct = productService.get(sUpdate[2]);
					if (null == aProduct) {
						addActionError("查无商品资料(或无该权限查看)");
						return "edit";
					} else {
						if (aProduct.getProductType() == 1 || aProduct.getProductType() == 6) {
							addActionError("商品型态不可为预购或N選M");
							return "edit";
						}
					}
					addOnProduct.setMainProductId(sUpdate[1]);
					addOnProduct.setAddOnProductId(sUpdate[2]);
					addOnProduct.setAddOnPrice(new BigDecimal(sUpdate[3]).setScale(1, BigDecimal.ROUND_FLOOR));
					addOnProduct.setStartDate(format.parse(sUpdate[4]));
					addOnProduct.setEndDate(format.parse(sUpdate[5]));
					addOnProduct.setIsEnable(sUpdate[6]);
					addOnProduct.setAddOnDesc(sUpdate[7]);
					addOnProduct.setApplyMemberRank(sUpdate[8]);
					productService.saveAddOnProduct(addOnProduct);
					logService.save(getClass().getSimpleName(), "save", addOnProduct);
				}
			}
		}
		return list();
	}

	/**
	 * 检视商品是否是同一供应商
	 * 
	 * @return
	 * @throws CoreException
	 */
	private boolean checkTheSameSupplier(String subProductId, String mainProductId) throws CoreException {
		boolean sameSupplier = false;
		Map<String, String> pdIdCheckMap = new HashMap<String, String>();
		Map<String, String> scmCheckMap = new HashMap<String, String>();
		Map<String, Map<String, String>> resultMap = new HashMap<String, Map<String, String>>();
		Product pdSuplier = productService.get(mainProductId);
		pdIdCheckMap.put(pdSuplier.getSupplierId(), pdSuplier.getSupplierId());
		scmCheckMap.put(pdSuplier.getIsScm(), pdSuplier.getSupplierId());
		criteria = new CommonCriteria();
		criteria.addEq("mainProductId", mainProductId);
		criteria.addEq("isEnable", "Y");
		criteria.addEq("isDelete", "N");
		addOnProductList = productService.getAddOnProductList(0, -1, criteria, null);
		if (addOnProductList.size() > 0) {// 已存在的AddOnProduct，由DB抓出
			for (int ipnm = 0; ipnm < addOnProductList.size(); ipnm++) {
				pdSuplier = productService.get(addOnProductList.get(ipnm).getAddOnProductId());
				resultMap = checkSameScmMap(pdSuplier, pdIdCheckMap, scmCheckMap);
			}
			if (StringUtils.isNotBlank(subProductId)) {
				pdSuplier = productService.get(subProductId);
				resultMap = checkSameScmMap(pdSuplier, pdIdCheckMap, scmCheckMap);
			}
		} else {// 新增時，由前端頁面帶入
			if (StringUtils.isNotBlank(subProductId)) {
				pdSuplier = productService.get(subProductId);
				resultMap = checkSameScmMap(pdSuplier, pdIdCheckMap, scmCheckMap);
			}
		}
		if (resultMap.get("pdIdCheckMap").size() == 1 && resultMap.get("scmCheckMap").size() == 1) {
			sameSupplier = true;
		} else {
			sameSupplier = false;
		}
		return sameSupplier;
	}

	Map<String, Map<String, String>> checkSameScmMap(Product product, Map<String, String> pdIdCheckMap,
			Map<String, String> scmCheckMap) {
		if (product.getIsScm().equalsIgnoreCase("N")) {
			if (!product.getSupplierId().equalsIgnoreCase("000000") && !product.getSupplierId().equalsIgnoreCase("000953")) {
				pdIdCheckMap.put(product.getSupplierId(), product.getSupplierId());
				scmCheckMap.put(product.getIsScm(), product.getSupplierId());
			}
		} else {
			pdIdCheckMap.put(product.getSupplierId(), product.getSupplierId());
			scmCheckMap.put(product.getIsScm(), product.getSupplierId());
		}
		Map<String, Map<String, String>> checkMap = new HashMap<String, Map<String, String>>();
		checkMap.put("pdIdCheckMap", pdIdCheckMap);
		checkMap.put("scmCheckMap", scmCheckMap);
		return checkMap;
	}

	/**
	 * @param addonId the addonId to set
	 */
	public void setAddonId(String addonId) {
		this.addonId = addonId;
	}

	/**
	 * @param addOnProduct the addOnProduct to set
	 */
	public void setAddOnProduct(AddOnProduct addOnProduct) {
		this.addOnProduct = addOnProduct;
	}

	/**
	 * @param addonProductIdParam the addonProductIdParam to set
	 */
	public void setAddonProductIdParam(String addonProductIdParam) {
		this.addonProductIdParam = addonProductIdParam;
	}

	/**
	 * @param addonproducts the addonproducts to set
	 */
	public void setAddonproducts(List<String> addonproducts) {
		this.addonproducts = addonproducts;
	}

	/**
	 * @param addOnProductsByMainId the addOnProductsByMainId to set
	 */
	public void setAddOnProductsByMainId(List<String> addOnProductsByMainId) {
		this.addOnProductsByMainId = addOnProductsByMainId;
	}

	/**
	 * @param addOnProductsByMainId2 the addOnProductsByMainId2 to set
	 */
	public void setAddOnProductsByMainId2(List<String> addOnProductsByMainId2) {
		this.addOnProductsByMainId2 = addOnProductsByMainId2;
	}

	/**
	 * @param addOnProductsByMainId3 the addOnProductsByMainId3 to set
	 */
	public void setAddOnProductsByMainId3(List<String> addOnProductsByMainId3) {
		this.addOnProductsByMainId3 = addOnProductsByMainId3;
	}

	/**
	 * @param addonstatus the addonstatus to set
	 */
	public void setAddonstatus(String addonstatus) {
		this.addonstatus = addonstatus;
	}

	/**
	 * @param finalAddOnData the finalAddOnData to set
	 */
	public void setFinalAddOnData(String finalAddOnData) {
		this.finalAddOnData = finalAddOnData;
	}

	public void setMainProduct(Product mainProduct) {
		this.mainProduct = mainProduct;
	}

	/**
	 * @param mainProductId the mainProductId to set
	 */
	public void setMainProductId(String mainProductId) {
		this.mainProductId = mainProductId;
	}

	/**
	 * @param mainProductIdParam the mainProductIdParam to set
	 */
	public void setMainProductIdParam(String mainProductIdParam) {
		this.mainProductIdParam = mainProductIdParam;
	}

	public void setMainSubFlag(String mainSubFlag) {
		this.mainSubFlag = mainSubFlag;
	}

	/**
	 * @param pager the pager to set
	 */
	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	/**
	 * @param product the product to set
	 */
	public void setProduct(Product product) {
		this.product = product;
	}

	/**
	 * @param productNameDataExist the productNameDataExist to set
	 */
	public void setProductNameDataExist(String productNameDataExist) {
		this.productNameDataExist = productNameDataExist;
	}

	/**
	 * @param productService the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setShelfMain(Shelf shelfMain) {
		this.shelfMain = shelfMain;
	}

	public void setShelfSub(Shelf shelfSub) {
		this.shelfSub = shelfSub;
	}

	public void setSubProduct(Product subProduct) {
		this.subProduct = subProduct;
	}

	public void setToday(String today) {
		this.today = today;
	}

	public String getMarkMainProductId() {
		return markMainProductId;
	}

	public void setMarkMainProductId(String markMainProductId) {
		this.markMainProductId = markMainProductId;
	}

	public List<AddOnProduct> getAddOnProductList() {
		return addOnProductList;
	}

	public void setAddOnProductList(List<AddOnProduct> addOnProductList) {
		this.addOnProductList = addOnProductList;
	}

	public String getEditAddOnPrice() {
		return editAddOnPrice;
	}

	public void setEditAddOnPrice(String editAddOnPrice) {
		this.editAddOnPrice = editAddOnPrice;
	}
}
